import 'dart:async';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/model/user.dart';
import 'package:image_picker/image_picker.dart';
import 'package:gzmall_app/mine/input_content.dart';

class PersonInfoPage extends StatefulWidget {
  @override
  PersonInfoPageState createState() {
    return new PersonInfoPageState();
  }
}

class PersonInfoPageState extends State<PersonInfoPage> {
  User _user = User.empty();

  @override
  void initState() {
    super.initState();
    _getUserInfoFromLocate();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: _createAppBar(),
      body: new Container(
        color: ColorCommon.grey2,
        child: new ListView(
          children: <Widget>[
            _getSettingItem(
              "账户头像",
              new Container(
                width: 35.0,
                height: 35.0,
                decoration: _user != null &&
                        _user.avatar != null &&
                        _user.avatar.isNotEmpty
                    ? new BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(100.0)),
                        image: new DecorationImage(
                            image: _image != null
                                ? new FileImage(_image)
                                : new CachedNetworkImageProvider(_user.avatar),
                            fit: BoxFit.fill),
                      )
                    : BoxDecoration(
                        color: Colors.grey,
                        borderRadius: BorderRadius.all(Radius.circular(100.0)),
                      ),
              ),
              19.0,
              const EdgeInsets.only(top: 10.0, bottom: 10.0),
              () {
                showCupertinoModalPopup(
                  context: context,
                  builder: (_) {
                    return CupertinoActionSheet(
                      actions: <Widget>[
                        CupertinoActionSheetAction(
                          onPressed: () {
                            _getImage(ImageSource.camera);
                            Navigator.of(context).pop();
                          },
                          child: Text("拍照"),
                        ),
                        CupertinoActionSheetAction(
                          onPressed: () {
                            _getImage(ImageSource.gallery);
                            Navigator.of(context).pop();
                          },
                          child: Text("相册"),
                        ),
                      ],
                      cancelButton: CupertinoActionSheetAction(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        child: Text("取消"),
                      ),
                    );
                  },
                );
              },
            ),
            _getSettingItem(
              "会员名",
              new Text(_user.nickname != null && _user.nickname.isNotEmpty
                  ? _user.nickname
                  : ""),
              15.0,
              const EdgeInsets.only(),
              () {
                Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                  return InputContentPage("设置会员名称");
                })).then((value) {
                  if (!mounted) return;
                  setState(() {
                    _user.nickname = value;
                    _updateUserInfo(_user.id, _user.nickname, _user.sex, null);
                  });
                });
              },
            ),
            // _getSettingItem(
            //   "我的二维码",
            //   new SizedBox(),
            //   15.0,
            //   const EdgeInsets.only(top: 1.0, bottom: 8.0),
            //   () {},
            // ),
            _getSettingItem(
              "性别",
              new Text(_user.sex != null && _user.sex == "male" ? "男" : "女"),
              15.0,
              const EdgeInsets.only(),
              () {
                showCupertinoModalPopup(
                  context: context,
                  builder: (_) {
                    return CupertinoActionSheet(
                      title: Text(
                        "选择性别",
                        style: TextStyle(fontSize: 20.0, color: Colors.blue),
                      ),
                      actions: <Widget>[
                        CupertinoActionSheetAction(
                          onPressed: () {
                            if (!mounted) return;
                            setState(() {
                              _user.sex = "male";
                              _updateUserInfo(
                                  _user.id, _user.nickname, _user.sex, null);
                            });
                            Navigator.of(context).pop();
                          },
                          child: Text("男"),
                        ),
                        CupertinoActionSheetAction(
                          onPressed: () {
                            if (!mounted) return;
                            setState(() {
                              _user.sex = "female";
                              _updateUserInfo(
                                  _user.id, _user.nickname, _user.sex, null);
                            });
                            Navigator.of(context).pop();
                          },
                          child: Text("女"),
                        ),
                      ],
                      cancelButton: CupertinoActionSheetAction(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        child: Text("取消"),
                      ),
                    );
                  },
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  _createAppBar() {
    return new AppBar(
      elevation: 0.0,
      title: new Text("设置"),
      leading: new IconButton(
        icon: new Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
      actions: <Widget>[],
    );
  }

  _getSettingItem(String text, Widget showWidget, double fontSize,
      EdgeInsetsGeometry margin, GestureTapCallback onTap) {
    return new GestureDetector(
      onTap: onTap,
      child: new Container(
        margin: margin,
        color: Colors.white,
        padding: const EdgeInsets.all(15.0),
        child: new Row(
          children: <Widget>[
            new Text(
              text,
              style: new TextStyle(fontSize: fontSize),
            ),
            new Expanded(
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  showWidget,
                  new Padding(
                    padding: const EdgeInsets.only(left: 10.0),
                    child: new Image.asset(
                      "images/right_arrow.png",
                      width: 10.0,
                      height: 10.0,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  File _image;

  Future _getImage(ImageSource source) async {
    var image = await ImagePicker.pickImage(source: source, maxWidth: 100.0);

    if (!mounted) return;
    setState(() {
      _image = image;
      _updateUserInfo(_user.id, _user.nickname, _user.sex, _image);
    });
  }

  _getUserInfoFromNet(int id) {
    NetUtil.get(context, Api.users + id.toString(), (data, message) {
      if (!mounted) return;
      setState(() {
        _user = User.fromJson(data);
        User.saveUserInfo(_user);
      });
    });
  }

  _getUserInfoFromLocate() async {
    await _user.getUserInfo();
    if (_user.id > 0) {
      _getUserInfoFromNet(_user.id);
    }
  }

  _updateUserInfo(int id, String nickname, String sex, File avatar) {
    Map<String, dynamic> params = {};
    params.addAll({
      "user[nickname]": nickname,
      "user[sex]": sex != null && sex.isNotEmpty ? sex : "female"
    });
    if (avatar != null) {
      params.addAll({"user[avatar]": MultipartFile.fromFileSync(avatar.path)});
    }
    FormData formData = new FormData.fromMap(params);
    NetUtil.put(context, Api.users + id.toString(), (data, message) {
      if (!mounted) return;
      setState(() {
        _user = User.fromJson(data);
        User.saveUserInfo(_user);
      });
    }, params: formData, isShowLoading: avatar != null);
  }
}
